import os
import requests
import tempfile

# 通过输入传入多个IP地址，每个IP地址之间用空格隔开，输入完毕后按回车键，脚本会自动执行
# 如果输入的IP地址不正确，脚本会提示错误信息，并退出
# 获取输入内容
ip_list = input("请输入要添加的IP地址，多个IP地址之间用空格隔开：")
# # 取出ip数组
ip_array = ip_list.split()
# ip数组去重
ip_array = list(set(ip_array))
# 通过接口获取密钥
response = requests.get('https://api.github.com/users/linshuboy/keys')
# 写入密钥到authorized_keys文件
sync_known_hosts_tmp_path = tempfile.mktemp()
authorized_keys_path = tempfile.mktemp()
authorized_keys_path_needle = open(authorized_keys_path, "w")
for key in response.json():
    authorized_keys_path_needle.write(key['key'] + '\n')
# 循环链接所有的IP地址
for ip in ip_array:
    tmp_path = tempfile.mktemp()
    os.system('scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=' +
              sync_known_hosts_tmp_path + ' root@' +
              ip + ':~/.ssh/id_rsa.pub ' + tmp_path)
    for line in open(tmp_path, "r"):
        authorized_keys_path_needle.write(line.split()[0] + ' ' + line.split()[1] + '\n')
    os.remove(tmp_path)
authorized_keys_path_needle.close()
for ip in ip_array:
    os.system('scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=' +
              sync_known_hosts_tmp_path + ' ' + authorized_keys_path + ' ' + 'root@' + ip + ':~/.ssh/authorized_keys')
    os.system('scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=' +
              sync_known_hosts_tmp_path + ' ' + sync_known_hosts_tmp_path + ' ' + 'root@' + ip + ':~/.ssh/known_hosts')
os.remove(authorized_keys_path)
os.remove(sync_known_hosts_tmp_path)
